<template>
  <el-card shadow="hover" class="mt-20">
    <el-button
      type="primary"
      :icon="Plus"
      :disabled="!categoryStore.category3Id"
      @click="showAddAttr"
      >添加属性</el-button
    >
    <el-table :data="attrList" border style="width: 100%" class="mt-20">
      <el-table-column type="index" label="序号" align="center" width="60" />
      <el-table-column prop="attrName" label="属性名称" width="150" />
      <el-table-column label="属性值列表">
        <template v-slot="{ row }">
          <el-tag
            class="ml-2 mr-10 mb-5"
            type="success"
            v-for="attr in row.attrValueList"
            :key="attr.id"
            >{{ attr.valueName }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            size="small"
            :icon="Edit"
            type="warning"
            title="修改"
            @click="showUpdateAttr(row)"
          ></el-button>
          <el-button
            size="small"
            type="danger"
            :icon="DeleteFilled"
            title="确定删除"
            @click="delAttr(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Components",
};
</script>

<script lang="ts" setup>
import { Plus, Edit, DeleteFilled } from "@element-plus/icons-vue";
import { useCategoryStore } from "@/stores/category";
import { watch, ref } from "vue";
import { getAttrListApi, delAttrApi } from "@/api/product/attr";
import type { AttrList, AttrsItem } from "@/api/product/model/attrModel";
import { useAttrStore } from "@/stores/attr";
import { ElMessage } from "element-plus";

const attrStore = useAttrStore();

const emit = defineEmits(["setIsShowAttrForm"]);

const categoryStore = useCategoryStore();
const attrList = ref<AttrList>([]);

const delAttr = async (id: number) => {
  await delAttrApi(id);
  ElMessage.success("删除成功");
  getAttrList();
};

const showAddAttr = () => {
  emit("setIsShowAttrForm", false);
  attrStore.$reset();
};
const showUpdateAttr = (row: AttrsItem) => {
  emit("setIsShowAttrForm", false);
  attrStore.attr = row;
};

const getAttrList = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
};
watch(
  () => categoryStore.category3Id,
  (category3Id) => {
    if (!category3Id) return;
    getAttrList();
  },
  {
    immediate: true,
  }
);
</script>

<style scoped></style>
